package com.example.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.handler.BusinessException;
import com.example.order.dto.UserReq;
import com.example.order.entity.User;
import com.example.order.mapper.UserMapper;
import com.example.order.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * UserServiceImpl class
 *
 * @author zhangl
 * @date 2023/3/9 15:07
 */
@Slf4j
@Service("orderUserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private static final String ORDER_CACHE_KEY = "orders.users";
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RBloomFilter userBloomFilter;


    @Override
    @Cacheable(value =ORDER_CACHE_KEY ,key = "#id")
    public User getUserById(long id) {
        User user = null;
        // 使用布隆过滤器
        if (userBloomFilter.contains(id)){
            user = userMapper.selectById(id);
        }
        //远程调用获取account-service的user数据
        if (user == null) {
           user = getRemoteUserById(id);
        }
        return user;
    }

    @Override
    public User createUser(UserReq userReq) {
        return null;
    }

    @Override
    public User updateUser(UserReq userReq) {
        return null;
    }

    @Override
    public void deleteUserById(int id) {

    }

    @Override
    public void syncUser(User user) {
        log.info("syncUser [{}]",user);
        if (user == null || user.getId() ==null) {
            return;
        }
        User user1 = user.selectById(user.getId());
        if (user1 != null){
            userMapper.update(user, new LambdaQueryWrapper<User>().eq(User::getId, user1.getId()));
        }else {
            userMapper.insert(user);
        }
        //更新缓存
        redisTemplate.opsForValue().set(String.format("%s::%s",ORDER_CACHE_KEY,user.getId()),user);
        userBloomFilter.add(user.getId());
    }

    /**
     * 远程获取用户信息
     * @param id
     * @return
     */
    private User getRemoteUserById(long id) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:8080/users/" + id, String.class);
        if (forEntity.getStatusCode() != HttpStatus.OK || forEntity.getBody() == null) {
            throw  BusinessException.createErrorException("查询失败，请稍后重试");
        }
        JSONObject jsonObject = (JSONObject) JSONObject.parse(forEntity.getBody());
        if ((Integer) jsonObject.get("code")== -1){
            throw  BusinessException.createErrorException(String.valueOf(jsonObject.get("msg")));
        }
        User user = JSONObject.toJavaObject((JSON) jsonObject.get("data"),User.class);
        return  user;
    }
}
